package com.browsesoft.htmlcomponent;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;

/**
 * 表示对树的某个节点进行操作的一组按钮
 * 
 * @author Browsesoft
 * @version 1.0
 */
public class HTMLButtonComponent extends HTMLBasicComponent {
	/**
	 * 操作的树节点的id号
	 */
	private Map parameters = new HashMap();

	/**
	 * 需要处理的元素
	 */
	protected LinkedList dealElements = new LinkedList();

	/**
	 * 构造器
	 * 
	 * @param parent
	 *            组件的父组件
	 * @throws Exception
	 */
	public HTMLButtonComponent(HTMLBasicComponent parent) throws Exception {
		super(parent);
	}

	/**
	 * 处理用户请求，将需要Model处理的内容提交给Model
	 * 
	 * @param request
	 *            客户端请求
	 * @throws java.lang.Exception
	 */
	public void init(HttpServletRequest request, Element e) throws Exception {
		super.init(request, e);
		parameters = request.getParameterMap();
	}

	/**
	 * 根据Model的内容更新需要处理的元素内容，在产生页面时要调用
	 * 
	 * @throws java.lang.Exception
	 */
	protected void updateElement() throws Exception {
		this.dealElements.clear();
		// this.parseElements(this.element);
		// 得到元素的treebuttons属性列表
		// ExtendElement.attrList.clear();
		dealElements = ExtendElement.findElements(element, "htmlbutton",
				"htmlbutton");
		Iterator iter = dealElements.iterator();
		while (iter.hasNext()) {
			// 取元素的名称
			Element dealElement = (Element) iter.next();
			String value = dealElement.getAttribute("onclick");
			Set keys = parameters.keySet();
			Iterator it = keys.iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				String[] v = (String[]) parameters.get(key);
				value = value.replaceAll("#" + key + "#", v[0]);
			}
			// 替换onclick中的nodeid
			dealElement.setAttribute("onclick", value);
		}
	}
}
